#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最简化的DeepSeek聊天程序
直接使用OpenAI兼容接口
"""

import os
import json
from pathlib import Path

def main():
    """主函数"""
    print("云顶之弈智能助手 - DeepSeek版")
    print("=" * 40)

    # 读取配置
    config_file = Path(__file__).parent / "config.json"
    if not config_file.exists():
        print("错误：config.json文件不存在")
        print("请先运行 python quick_setup.py 配置API密钥")
        return

    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)

        api_key = config.get('openai_api_key')
        api_base = config.get('openai_api_base', 'https://api.deepseek.com')
        model = config.get('model', 'deepseek-chat')

        if not api_key:
            print("错误：未找到API密钥")
            return

        print(f"配置加载成功")
        print(f"模型: {model}")
        print(f"API地址: {api_base}")
        print()

        # 测试API连接
        print("正在测试API连接...")
        try:
            from openai import OpenAI

            client = OpenAI(
                api_key=api_key,
                base_url=api_base
            )

            # 测试调用
            response = client.chat.completions.create(
                model=model,
                messages=[
                    {"role": "system", "content": "你是一个专业的云顶之弈智能助手。"},
                    {"role": "user", "content": "你好，请简单介绍一下你自己"}
                ],
                max_tokens=200,
                temperature=0.1
            )

            print("API连接成功！")
            test_answer = response.choices[0].message.content
            safe_test_answer = test_answer.encode('ascii', errors='ignore').decode('ascii')
            print(f"测试回复: {safe_test_answer}")
            print()

        except Exception as e:
            print(f"API连接失败: {e}")
            return

        # 开始聊天循环
        print("开始对话！输入 '退出' 结束对话")
        print("-" * 40)

        while True:
            try:
                user_input = input("\n您的问题: ").strip()

                if not user_input:
                    continue

                if user_input.lower() in ['退出', 'exit', 'q', 'quit']:
                    print("感谢使用，再见！")
                    break

                # 调用API
                print("DeepSeek正在思考...")
                response = client.chat.completions.create(
                    model=model,
                    messages=[
                        {"role": "system", "content": """你是一个专业的云顶之弈智能助手，擅长回答各种问题。

你的能力包括：
1. 回答关于云顶之弈游戏的问题
2. 分析最新的科技趋势和新闻
3. 提供实用的建议和信息
4. 进行多轮对话

请用中文回答，回答要准确、有用、易于理解。"""},
                        {"role": "user", "content": user_input}
                    ],
                    max_tokens=1000,
                    temperature=0.1
                )

                answer = response.choices[0].message.content
                # 清理可能导致编码问题的字符
                safe_answer = answer.encode('ascii', errors='ignore').decode('ascii')
                print(f"\nDeepSeek回答:")
                print(safe_answer)
                print("\n" + "-" * 40)

            except KeyboardInterrupt:
                print("\n程序被用户中断")
                break
            except Exception as e:
                print(f"处理出错: {e}")
                continue

    except Exception as e:
        print(f"程序异常: {e}")

if __name__ == "__main__":
    main()